package com.lee.dutylower.task;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.SystemClock;

import com.lee.dutylower.MyApplication;
import com.lee.dutylower.db.greenEntity.PostRecord;
import com.lee.dutylower.db.greenEntity.Sentry;
import com.lee.dutylower.db.greenEntity.Soldier;
import com.lee.dutylower.db.greenEntity.SquadRecord;
import com.lee.dutylower.db.greenEntity.Times;
import com.lee.dutylower.db.greendao.PostRecordDao;
import com.lee.dutylower.db.greendao.SentryDao;
import com.lee.dutylower.db.greendao.SoldierDao;
import com.lee.dutylower.db.greendao.SquadRecordDao;
import com.lee.dutylower.db.greendao.TimesDao;
import com.lee.dutylower.domain.SentryTypeEnum;
import com.lee.dutylower.domain.SquadTypeEnum;
import com.lee.dutylower.utils.LogUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

/**
 * Created by lijie on 2017/5/16.
 */

public class ScheduleTask extends AsyncTask<Void, String, List<PostRecord>> {
    private ProgressDialog mProgressDialog = null;
    private Activity context;
    private PostRecordDao postRecordDao;
    private SquadRecordDao squadRecordDao;
    private SoldierDao soldierDao;
    private SentryDao sentryDao;
    private TimesDao timesDaoDao;
    private List<Times> timesList;
    //上午班全是一个人的哨位
    private List<Sentry> sentries_45;
    //一个半小时一个人的哨位
    private List<Sentry> sentries_15;
    //白天一个人的哨位 值班版专属
    private List<Sentry> sentries_90;
    //上岗班集合
    private List<SquadRecord> onTypeSquad;
    //值班版集合
    private List<SquadRecord> dutyTypeSquad;
    //补岗班集合
    private List<SquadRecord> restTypeSquad;

    //派位表集合
    private List<PostRecord> postRecordDBs;

    //数据库各个上岗班人员集合
    private List<Soldier> soldiersOn1;
    private List<Soldier> soldiersOn2;
    private List<Soldier> soldiersOn3;

    //45型哨位 1.2.3为第一期 FirstTime 上午班,SecondTime 中午班，ThirdTime 下午班
    private LinkedList<Soldier> soldier_FirstTimes_45_Period;
    //45型哨位 4.5为第二期
    private LinkedList<Soldier> soldier_SecondTimes_45_Period;
    private LinkedList<Soldier> soldier_SecondTimes_45_Period_9;
    private LinkedList<Soldier> soldier_SecondTimes_45_Period_8;
    private LinkedList<Soldier> soldier_FirstTimes_45_Period_10_11;
    private LinkedList<Soldier> soldier_ThirdTimes_45_Period;
    private LinkedList<Soldier> soldier_ThirdTimes_45_Period_12_13;
    private LinkedList<Soldier> soldier_SecondTimes_45_Period_14_15;
    private LinkedList<Soldier> soldier_FirstTimes_15_Period;
    private LinkedList<Soldier> soldier_T10_T15_15_Period;
    private LinkedList<Soldier> soldier_FirstTimes_90_Period;

    private List<Soldier> soldierRest;
    private List<Soldier> soldierDuty;

    private Handler handler;
    private int dayofweek;


    public ScheduleTask(Activity context, Handler handler, int dayofweek) {
        this.context = context;
        this.handler = handler;
        this.dayofweek = dayofweek;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        postRecordDBs = new ArrayList<>();

        soldier_FirstTimes_45_Period = new LinkedList<>();
        soldier_SecondTimes_45_Period = new LinkedList<>();
        soldier_SecondTimes_45_Period_8 = new LinkedList<>();
        soldier_SecondTimes_45_Period_9 = new LinkedList<>();
        soldier_FirstTimes_45_Period_10_11 = new LinkedList<>();
        soldier_ThirdTimes_45_Period_12_13 = new LinkedList<>();
        soldier_SecondTimes_45_Period_14_15 = new LinkedList<>();


        soldier_ThirdTimes_45_Period = new LinkedList<>();
        soldier_FirstTimes_15_Period = new LinkedList<>();
        soldier_T10_T15_15_Period = new LinkedList<>();
        soldier_FirstTimes_90_Period = new LinkedList<>();

        postRecordDao = MyApplication.getApplication().getDaoSession().getPostRecordDao();
        squadRecordDao = MyApplication.getApplication().getDaoSession().getSquadRecordDao();
        soldierDao = MyApplication.getApplication().getDaoSession().getSoldierDao();
        sentryDao = MyApplication.getApplication().getDaoSession().getSentryDao();
        timesDaoDao = MyApplication.getApplication().getDaoSession().getTimesDao();

        mProgressDialog = new ProgressDialog(context);
        // 设置进度条风格，风格为圆形，旋转的
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        // 设置ProgressDialog 提示信息
        mProgressDialog.setMessage("正在准备数据，请稍等。。。");

        // 设置ProgressDialog 的进度条是否不明确
        mProgressDialog.setIndeterminate(false);
        // 设置ProgressDialog 是否可以按退回按键取消
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();

        //读取所有的时间段
        timesList = timesDaoDao.queryBuilder().build().list();
        //数据库读取相关类型的哨位

        sentries_45 = sentryDao.queryBuilder()
                .where(SentryDao.Properties.Sentry_type.eq(SentryTypeEnum.THREE_QUARTER.getType()))
                .build().list();
        sentries_15 = sentryDao.queryBuilder()
                .where(SentryDao.Properties.Sentry_type.eq(SentryTypeEnum.QUARTER.getType()))
                .build().list();
        sentries_90 = sentryDao.queryBuilder()
                .where(SentryDao.Properties.Sentry_type.eq(SentryTypeEnum.NINE_QUARTER.getType()))
                .build().list();
        //读取三种班次对应的班级

        onTypeSquad = squadRecordDao.queryBuilder()
                .where(SquadRecordDao.Properties.SquadType.eq(SquadTypeEnum.OnSquad.getType()))
                .build().list();
        dutyTypeSquad = squadRecordDao.queryBuilder()
                .where(SquadRecordDao.Properties.SquadType.eq(SquadTypeEnum.DutySquad.getType()))
                .build().list();
        restTypeSquad = squadRecordDao.queryBuilder()
                .where(SquadRecordDao.Properties.SquadType.eq(SquadTypeEnum.RestSquad.getType()))
                .build().list();

        //集合顺序调整
        LinkedList<SquadRecord> linkedList = new LinkedList<>();
        linkedList.addAll(onTypeSquad);
        for (int i = 1; i < dayofweek; i++) {
            SquadRecord last = linkedList.pollLast();
            linkedList.addFirst(last);
        }

        //遍历获取上岗班每个班的人员集合
        soldiersOn1 = linkedList.get(0).getSquad().getSoldiers();
        soldiersOn2 = linkedList.get(1).getSquad().getSoldiers();
        soldiersOn3 = linkedList.get(2).getSquad().getSoldiers();

        //获取补岗班每个班的人员集合
        soldierRest = restTypeSquad.get(0).getSquad().getSoldiers();

        //获取值班版人员集合
        soldierDuty = dutyTypeSquad.get(0).getSquad().getSoldiers();

    }

    @Override
    protected List<PostRecord> doInBackground(Void... params) {
        /**
         * -----------------------------------------------------------------------------------------------------------------------------------
         * 45类哨位 分配
         */
        int cursor45 = 0;
        //对哨位是45的进行遍历排序
        for (Sentry sentryDB : sentries_45) {

            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }

            //遍历每一个时间段，按时间顺序进行排序
            for (Times timesDB : timesList) {
                //时间段7：30-9：00 给哨位类型45 安排人员
                if (timesDB.getTimeID() == 1) {

                    //获取可站迟哨位的人员集合
                    List<Soldier> canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn1) {
                        if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                    }
                    editListAndRecord15OR45(canGuardList, restCanGuardList, soldier_FirstTimes_45_Period, sentryDB, timesDB);
                }

                //根据游标来取得相关人员 1，2，3id时间 由一个士兵完成
                if (timesDB.getTimeID() > 1 && timesDB.getTimeID() <= 3) {
                    chooseListAndRecord(cursor45, soldier_FirstTimes_45_Period, sentryDB, timesDB);
                }

                //times id in 4-5 中午
                if (timesDB.getTimeID() > 3 && timesDB.getTimeID() <= 5) {
                    List<Soldier> canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn2) {
                        if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                    }
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 4:
                            editListAndRecord15OR45(canGuardList, restCanGuardList, soldier_SecondTimes_45_Period, sentryDB, timesDB);
                            break;
                        case 5:
                            chooseListAndRecord(cursor45, soldier_SecondTimes_45_Period, sentryDB, timesDB);
                            break;
                    }

                }

                //times id in 6-7
                if (timesDB.getTimeID() > 5 && timesDB.getTimeID() <= 7) {
                    List<Soldier> canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn3) {
                        if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                    }
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 6:
                            editListAndRecord15OR45(canGuardList, restCanGuardList, soldier_ThirdTimes_45_Period, sentryDB, timesDB);
                            break;
                        case 7:
                            chooseListAndRecord(cursor45, soldier_ThirdTimes_45_Period, sentryDB, timesDB);
                            break;
                    }

                }
            }
            cursor45 = cursor45 + 1;
        }
        //对18：30 到 20：00 45 类型哨位 进行排班
        List<Sentry> spSentrys45T18_20 = getT18_20Sentry();
        for (int i = 0; i < spSentrys45T18_20.size(); i++) {
            Sentry sentryDB = spSentrys45T18_20.get(i);
            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }
            for (Times timesDB : timesList) {
                if (timesDB.getTimeID() == 8){
                    List<Soldier> canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn2) {
                        if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                    }
                    //canGuardList.removeAll(soldier_SecondTimes_45_Period);

                    if (sentryDB.getSentry_id() == 6){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    } else if (sentryDB.getSentry_id() == 10){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    }else if (sentryDB.getSentry_id() == 11){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    }else {
                        editListAndRecord15OR45(canGuardList,restCanGuardList, soldier_SecondTimes_45_Period_8, sentryDB, timesDB);
                    }
                }
            }
        }

        //对20：00 到 22：00 45 类型哨位 进行排班
        List<Sentry> spSentrys45T20_22 = getT20_22Sentry();
        for (int i = 0; i < spSentrys45T20_22.size(); i++) {
            Sentry sentryDB = spSentrys45T20_22.get(i);
            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }
            for (Times timesDB : timesList) {
                if (timesDB.getTimeID() == 9){
                    List<Soldier> canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn2) {
                        if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                    }
                    //canGuardList.removeAll(soldier_SecondTimes_45_Period);
                    if (sentryDB.getSentry_id() == 6){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    } else if (sentryDB.getSentry_id() == 10){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    }else if (sentryDB.getSentry_id() == 11){
                        LogUtils.e("ScheduleTask",sentryDB.getSentry_name());
                    }else {
                        editListAndRecord15OR45(canGuardList,restCanGuardList, soldier_SecondTimes_45_Period_9, sentryDB, timesDB);
                    }

                }
            }
        }


        cursor45 = 0;
        for (int i = 0; i < sentries_45.size(); i++) {

            Sentry sentryDB = sentries_45.get(i);
            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }

            for (Times timesDB : timesList) {
                if(timesDB.getTimeID()>9 && timesDB.getTimeID()<=11){
                    //20:00 - 24:00  24:00 - 01:30 上午班来
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 10:
                            soldier_FirstTimes_45_Period_10_11 = ListSort(soldier_FirstTimes_45_Period);
                            chooseListAndRecord(cursor45, soldier_FirstTimes_45_Period_10_11, sentryDB, timesDB);
                            break;
                        case 11:
                            chooseListAndRecord(cursor45, soldier_FirstTimes_45_Period_10_11, sentryDB, timesDB);
                            break;
                    }
                }else if(timesDB.getTimeID()>11 && timesDB.getTimeID()<=13){
                    //01:30 - 03:00  03:00 - 04:30 下午班来
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 12:
                            soldier_ThirdTimes_45_Period_12_13 = ListSort(soldier_ThirdTimes_45_Period);
                            chooseListAndRecord(cursor45, soldier_ThirdTimes_45_Period_12_13, sentryDB, timesDB);
                            break;
                        case 13:
                            chooseListAndRecord(cursor45, soldier_ThirdTimes_45_Period_12_13, sentryDB, timesDB);
                            break;
                    }
                } else if(timesDB.getTimeID()>13 && timesDB.getTimeID()<=15){
                    //04:30 - 06:00  06:00 - 07:30 中午搬来
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 14:
                            LinkedList<Soldier> temp = ListSort(soldier_SecondTimes_45_Period);
                            soldier_SecondTimes_45_Period_14_15 = ListSort(temp);
                            chooseListAndRecord(cursor45, soldier_SecondTimes_45_Period_14_15, sentryDB, timesDB);
                            break;
                        case 15:
                            chooseListAndRecord(cursor45, soldier_SecondTimes_45_Period_14_15, sentryDB, timesDB);
                            break;
                    }
                }
            }
            cursor45 = cursor45 + 1;
        }

        /**
         * 45类哨位 分配结束
         * -----------------------------------------------------------------------------------------------------------------------------------
         *
         * 15类哨位分配开始
         */

        //对哨位是15的进行遍历排序 先进行 0-3
        for (int i = 0; i < sentries_15.size(); i++) {
            Sentry sentryDB = sentries_15.get(i);
            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }

            //遍历每一个时间段，按时间顺序进行排序
            for (Times timesDB : timesList) {

                //前三个时间段 给哨位类型15 安排人员
                if (timesDB.getTimeID() <= 3) {

                    //获取可站迟哨位的人员集合
                    List<Soldier> canGuardList = new ArrayList<>();
                    int l = (int) (timesDB.getTimeID()+0);
                    switch (l) {
                        case 1:
                            canGuardList.clear();
                            for (Soldier soldierDB : soldiersOn1) {
                                if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                            }
                            break;
                        case 2:
                            canGuardList.clear();
                            for (Soldier soldierDB : soldiersOn2) {
                                if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                            }
                            break;
                        case 3:
                            canGuardList.clear();
                            for (Soldier soldierDB : soldiersOn3) {
                                if (soldierDB.canGuard(sentryDB)) canGuardList.add(soldierDB);
                            }
                            break;
                    }
                    List<Soldier> temp = new ArrayList<>();
                    temp.addAll(restCanGuardList);
                    temp.addAll(canGuardList);
                    temp.removeAll(soldier_ThirdTimes_45_Period);
                    editListAndRecord15OR45(temp, temp, soldier_FirstTimes_15_Period, sentryDB, timesDB);
                    SystemClock.sleep(1000);
                }
            }
        }

        List<Soldier> canGuardList = null;
        //必须等到 15类的哨位 所有和 0-3的ID的平分配完成 顺序很重要
        for (int i = 0; i < sentries_15.size(); i++) {
            Sentry sentryDB = sentries_15.get(i);
            //补岗班可站哨位人员集合
            List<Soldier> restCanGuardList = new ArrayList<>();
            for (Soldier soldierDB : soldierRest) {
                if (soldierDB.canGuard(sentryDB)) restCanGuardList.add(soldierDB);
            }
            for (Times timesDB : timesList) {
                //一个半小时 4-6时间段 人员分配
                if (timesDB.getTimeID() <= 6 && timesDB.getTimeID()>3){
                    if (i >= 0 && i != (sentries_15.size()-1)){
                        int start = (i+1)*3;
                        int index = (int) (start+(timesDB.getTimeID()-4));
                        chooseListAndRecord15(index,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }else {
                        int start = (i-(sentries_15.size()-1));
                        int index = (int) (start+(timesDB.getTimeID()-4));
                        chooseListAndRecord15(index,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }
                }
                //一个半小时 7-9时间段 人员分配
                if (timesDB.getTimeID() <= 9 && timesDB.getTimeID()>6){
                    if (i >= 0 && i != (sentries_15.size()-1)){
                        int index = (int) (timesDB.getTimeID()-7);
                        chooseListAndRecord15(index,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }else {
                        int index = (int) (timesDB.getTimeID()-4);
                        chooseListAndRecord15(index,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }
                }
                //10 - 11 时间段 选择First班内的的人员
                if (timesDB.getTimeID() == 10 || timesDB.getTimeID() == 11){
                    //找出First班中可以值哨位的集合 根据大小判断如何选择
                    canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn1) {
                        if (soldierDB.canGuard(sentryDB) && !soldier_FirstTimes_15_Period.contains(soldierDB)){
                            canGuardList.add(soldierDB);
                        }
                    }
                    //存在新的人员 使用新的人员 若没有则交换白天人员
                    if (canGuardList.size()>1){
                        if (timesDB.getTimeID() == 10){
                            canGuardList.removeAll(soldier_T10_T15_15_Period);
                            editListAndRecord15OR45(canGuardList,restCanGuardList, soldier_T10_T15_15_Period,sentryDB,timesDB);
                        }else {
                            if (3*i < soldier_T10_T15_15_Period.size()){
                                chooseListAndRecord15(3*i, soldier_T10_T15_15_Period,sentryDB,timesDB);
                            }else {
                                chooseListAndRecord15(i*3,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                            }
                        }
                    }else {
                        chooseListAndRecord15(i*3,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }
                }
                //12 - 13 时间段 选择Third班内的的人员
                if (timesDB.getTimeID() <= 13 && timesDB.getTimeID()>11){
                    //找出Third班中可以值哨位的集合 根据大小判断如何选择
                    canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn3) {
                        if (soldierDB.canGuard(sentryDB) && !soldier_FirstTimes_15_Period.contains(soldierDB)){
                            canGuardList.add(soldierDB);
                        }
                    }
                    //存在新的人员 使用新的人员 若没有则交换白天人员
                    if (canGuardList.size()>1){
                        if (timesDB.getTimeID() == 12){
                            canGuardList.removeAll(soldier_T10_T15_15_Period);
                            editListAndRecord15OR45(canGuardList,restCanGuardList, soldier_T10_T15_15_Period,sentryDB,timesDB);
                        }else {
                            if (3*i+1 < soldier_T10_T15_15_Period.size()){
                                chooseListAndRecord15(3*i+1, soldier_T10_T15_15_Period,sentryDB,timesDB);
                            }else {
                                chooseListAndRecord15(i*3+2,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                            }
                        }
                    }else {
                        chooseListAndRecord15(i*3+2,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }
                }

                //12 - 13 时间段 选择Second班内的的人员
                if (timesDB.getTimeID() <= 15 && timesDB.getTimeID()>13){
                    //找出Third班中可以值哨位的集合 根据大小判断如何选择
                    canGuardList = new ArrayList<>();
                    for (Soldier soldierDB : soldiersOn2) {
                        if (soldierDB.canGuard(sentryDB) && !soldier_FirstTimes_15_Period.contains(soldierDB)){
                            canGuardList.add(soldierDB);
                        }
                    }
                    //存在新的人员 使用新的人员 若没有则交换白天人员
                    if (canGuardList.size()>1){
                        if (timesDB.getTimeID() == 14){
                            canGuardList.removeAll(soldier_T10_T15_15_Period);
                            editListAndRecord15OR45(canGuardList,restCanGuardList, soldier_T10_T15_15_Period,sentryDB,timesDB);
                        }else {
                            if (3*i+2 < soldier_T10_T15_15_Period.size()){
                                chooseListAndRecord15(3*i+2, soldier_T10_T15_15_Period,sentryDB,timesDB);
                            }else {
                                chooseListAndRecord15(i*3+1,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                            }
                        }
                    }else {
                        chooseListAndRecord15(i*3+1,soldier_FirstTimes_15_Period,sentryDB,timesDB);
                    }
                }
            }
        }

        //对哨位是全天类的进行遍历排序 选着对象是值班版人员
        for (Sentry sentryDB : sentries_90) {
            //遍历每一个时间段，按时间顺序进行排序
            for (Times timesDB : timesList) {
                //时间段7：30-9：00 给哨位类型90 安排人员
                if (timesDB.getTimeID() == 1) {
                    editListAndRecord90(soldier_FirstTimes_90_Period, sentryDB, timesDB);
                }
                if (timesDB.getTimeID() == 2 && sentryDB.getSentry_name().equals("302")) {
                    editListAndRecord90(soldier_FirstTimes_90_Period, sentryDB, timesDB);
                }
            }
        }

        publishProgress("soldier_FirstTimes_45_Period", soldier_FirstTimes_45_Period.size() + "", "`````");
        publishProgress("soldier_SecondTimes_45_Period", soldier_SecondTimes_45_Period.size() + "", "`````");
        publishProgress("soldier_FirstTimes_15_Period", soldier_FirstTimes_15_Period.size() + "", "`````");
        publishProgress("soldier_FirstTimes_90_Period", soldier_FirstTimes_90_Period.size() + "", "`````");
        publishProgress("postRecordDBssize", postRecordDBs.size() + "", "`````");

        for (PostRecord postRecordDB : postRecordDBs) {
            postRecordDB.setDayofweek(dayofweek);
            publishProgress("写入数据", postRecordDB.getSentryID() + "", "```"+dayofweek+"``");
            postRecordDao.insert(postRecordDB);
        }

        return postRecordDBs;
    }


    /**
     * @param soldier_Times_Num_Period 装载人员分配集合
     * @param sentryDB                 the sentry db
     * @param timesDB                  the times db
     */
    public void editListAndRecord90(LinkedList<Soldier> soldier_Times_Num_Period, Sentry sentryDB, Times timesDB) {
        PostRecord postRecordDB = new PostRecord();
        //装载数据
        postRecordDB.setSentryID(sentryDB.getSentry_id());
        postRecordDB.setTimesID(timesDB.getTimeID());
        int count = 0;
        Soldier so = chooseSoldierFromRest(soldierDuty, count, soldier_Times_Num_Period);
        if (so != null) {
            //添加到集合以便操作
            soldier_Times_Num_Period.add(so);
            //进度刷新
            publishProgress(so.getSName(), sentryDB.getSentry_name(), timesDB.getStartTime() + "--" + timesDB.getEndTime());
            //给排位表类赋值人员ID
            postRecordDB.setGuiderID(so.getSID());
            postRecordDBs.add(postRecordDB);
            // TODO: 2017/5/19 插入数据库
            so.setGuardTimes(so.getGuardTimes()+1);
            soldierDao.update(so);

        } else {
            publishProgress("为找到合适人员", sentryDB.getSentry_name(), "");
        }
    }

    public void editListAndRecord15OR45(List<Soldier> canGuardList, List<Soldier> restCanGuardList, LinkedList<Soldier> soldier_Times_Num_Period, Sentry sentryDB, Times timesDB) {
        PostRecord postRecordDB = new PostRecord();
        //装载数据
        postRecordDB.setSentryID(sentryDB.getSentry_id());
        postRecordDB.setTimesID(timesDB.getTimeID());
        int count = 0;
        Soldier so = chooseSoldier(canGuardList, count, restCanGuardList, soldier_Times_Num_Period);
        if (so != null) {
            //添加到集合以便操作
            soldier_Times_Num_Period.add(so);
            //进度刷新
            publishProgress(so.getSName(), sentryDB.getSentry_name(), timesDB.getStartTime() + "--" + timesDB.getEndTime());
            //给排位表类赋值人员ID
            postRecordDB.setGuiderID(so.getSID());
            postRecordDBs.add(postRecordDB);
            // TODO: 2017/5/19 插入数据库

        } else {
            publishProgress("为找到合适人员", sentryDB.getSentry_name(), "");
        }
    }

    public void chooseListAndRecord(int cursor, LinkedList<Soldier> soldier_Times_Num_Period, Sentry sentryDB, Times timesDB) {
        PostRecord postRecordDB = new PostRecord();
        //装载数据
        postRecordDB.setSentryID(sentryDB.getSentry_id());
        postRecordDB.setTimesID(timesDB.getTimeID());
        Soldier so = soldier_Times_Num_Period.get(cursor);
        postRecordDB.setGuiderID(so.getSID());
        postRecordDBs.add(postRecordDB);
        // TODO: 2017/5/19 插入数据库
        publishProgress(so.getSName(), sentryDB.getSentry_name(), timesDB.getStartTime() + "--" + timesDB.getEndTime());
    }

    public void chooseListAndRecord15(int index, LinkedList<Soldier> soldier_Times_Num_Period, Sentry sentryDB, Times timesDB) {
        PostRecord postRecordDB = new PostRecord();
        //装载数据
        postRecordDB.setSentryID(sentryDB.getSentry_id());
        postRecordDB.setTimesID(timesDB.getTimeID());
        Soldier so = soldier_Times_Num_Period.get(index);
        postRecordDB.setGuiderID(so.getSID());
        postRecordDBs.add(postRecordDB);
        // TODO: 2017/5/19 插入数据库
        publishProgress(so.getSName(), sentryDB.getSentry_name(), timesDB.getStartTime() + "--" + timesDB.getEndTime());
    }

    //人员选择算法
    public Soldier chooseSoldier(List<Soldier> canGuardList, int count, List<Soldier> restCanGuardList, List<Soldier> contains) {
        Soldier result = null;
        List<Soldier> noChooseList = new ArrayList<>();
        List<Soldier> hasChooseList = new ArrayList<>();
        List<Soldier> temp = new ArrayList<>();
        temp.addAll(canGuardList);
        temp.removeAll(contains);

        if (temp.size() > 0){
            for (Soldier soldier : temp) {
                Soldier sDB = soldierDao.queryBuilder().where(SoldierDao.Properties.SID.eq(soldier.getSID())).build().unique();
                if (sDB.getGuardTimes() == 0){
                    noChooseList.add(soldier);
                }else {
                    soldier.setGuardTimes(sDB.getGuardTimes());
                    hasChooseList.add(soldier);
                }
            }
            if (noChooseList.size() == 0){
                TreeSet<Soldier> treeSet = new TreeSet<>();
                treeSet.addAll(hasChooseList);
                result = treeSet.pollFirst();
            }else {
                //产生0到列表大小的随机数
                int random = (int) (Math.random() * (noChooseList.size()-1));
                result = noChooseList.get(random);
            }
        }else {
            //从补岗班选择
            int restcount = 0;
            result = chooseSoldierFromRest(restCanGuardList, restcount, contains);
        }
        //将选中的人员进行计数cun
        if (result != null){
            result.setGuardTimes(result.getGuardTimes()+1);
            soldierDao.update(result);
        }
        return result;

    }

    //从其他班选择值班人员
    public Soldier chooseSoldierFromRest(List<Soldier> restCanGuardList, int count, List<Soldier> contains) {
        Soldier result = null;

        List<Soldier> noChooseList = new ArrayList<>();
        List<Soldier> hasChooseList = new ArrayList<>();
        List<Soldier> temp = new ArrayList<>();
        temp.addAll(restCanGuardList);
        temp.removeAll(contains);

        if (temp.size() > 0){
            for (Soldier soldier : temp) {
                Soldier sDB = soldierDao.queryBuilder().where(SoldierDao.Properties.SID.eq(soldier.getSID())).build().unique();
                if (sDB.getGuardTimes() == 0){
                    noChooseList.add(soldier);
                }else {
                    soldier.setGuardTimes(sDB.getGuardTimes());
                    hasChooseList.add(soldier);
                }
            }
            if (noChooseList.size() == 0){
                TreeSet<Soldier> treeSet = new TreeSet<>();
                treeSet.addAll(hasChooseList);
                result = treeSet.pollFirst();
                return result;
            }else {
                //产生0到列表大小的随机数
                int random = (int) (Math.random() * (noChooseList.size()-1));
                result = noChooseList.get(random);
                return result;
            }
        }else {
            return result;
        }

    }


    public boolean isContain(List<Soldier> canGuardList, Soldier result) {
        for (Soldier soldierDB : canGuardList) {
            if (soldierDB.getSID().longValue() == result.getSID().longValue()) {
                return true;
            }
        }
        return false;
    }

    public LinkedList<Soldier> ListSort(LinkedList<Soldier> oldList){
        LinkedList<Soldier> result = new LinkedList<>();
        //=0  使用已经匹配过得中午班 进行分配,先进行排序
        Soldier lSo = oldList.getLast();
        result.addFirst(lSo);
        result.addAll(oldList);
        result.removeLast();
        return result;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        mProgressDialog.setMessage(values[0] + "---" + values[1] + "---" + values[2]);
        LogUtils.e("ScheduleTask", values[0] + "---" + values[1] + "---" + values[2]);
    }

    @Override
    protected void onPostExecute(List<PostRecord> result) {
        super.onPostExecute(result);
        if (dayofweek == 7){
            handler.sendEmptyMessage(1);
        }else {
            handler.sendEmptyMessage(0);
        }
        mProgressDialog.cancel();
    }

    public List<Sentry> getT18_20Sentry(){
        SentryDao sentryDao = MyApplication.getApplication().getDaoSession().getSentryDao();
        List<Sentry> result =  sentryDao.queryBuilder()
                .where(SentryDao.Properties.Sentry_id.in(1L,2L,4L,6L,7L,8L,10L,11L),
                        SentryDao.Properties.Sentry_type.eq(45))
                .build().list();
        if (result == null){
            result = new ArrayList<>();
            return result;
        }else {
            return result;
        }
    }

    public List<Sentry> getT20_22Sentry(){
        SentryDao sentryDao = MyApplication.getApplication().getDaoSession().getSentryDao();
        List<Sentry> result =  sentryDao.queryBuilder()
                .where(SentryDao.Properties.Sentry_id.in(1L,2L,4L,7L,8L,9L,10L),
                        SentryDao.Properties.Sentry_type.eq(45))
                .build().list();
        if (result == null){
            result = new ArrayList<>();
            return result;
        }else {
            return result;
        }
    }
}
